<?php

class Register implements Action {

    private $name;
    private $bday;
    private $username;
    private $password;

    public function setParams($param = null) {
        $this->name = $_POST['name'];
        $this->bday = $_POST['birthdate'];
        $this->username = $_POST['username'];
        $this->password = $_POST['password'];
    }

    public function validate($response) {
        if ($_SESSION['admin'] == '0') {
            $response->addError("You are not allowed to register instructors!");
        }
        if ($this->name == "") {
            $response->addError("Name missing!");
        }
        if ($this->bday == "") {
            $response->addError("Birthday missing!");
        }
        if ($this->username == "") {
            $response->addError("Username missing!");
        }
        if ($this->password == "") {
            $response->addError("Password missing!");
        }
    }

    public function execute($response) {

        $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
        mysql_select_db(DB_NAME, $con) or die(mysql_error());

        $sql = "SELECT username FROM management_login WHERE username='$this->username'";
        if (mysql_num_rows(mysql_query($sql, $con)) > 0) {
            $response->addError("Username already used");
            return;
        }

        $sql = "INSERT INTO management (name, bday) VALUES ('$this->name','$this->bday')";
        mysql_query($sql, $con) or die(mysql_error());

        $sql = "INSERT INTO management_login (admin_id, username, password, permission) 
                VALUES (LAST_INSERT_ID(),'$this->username', '$this->password', '0')";
        mysql_query($sql, $con) or die(mysql_error());

        $response->set('name', $this->name);
        $response->set('bday', $this->bday);
        $response->set('username', $this->username);
        $response->set('values', $response->getValues());
    }

    public function getContentType() {
        return JSON;
    }

    public function getHTTPMethod() {
        return POST;
    }

}

?>
